# from django import http
# from django.core.paginator import Paginator, EmptyPage
# from django.shortcuts import render
#
# # Create your views here.
# from django.views import View
#
# from goods.models import GoodsCategory, SKU
# from goods.utils import get_categories, get_breadcrumb
#
#
# class ListView(View):
#      """商品列表页"""
#
#      def get(self, request, category_id, page_num):
#         """提供商品列表页"""
#         # 判断category_id是否正确
#         try:
#             # 获取三级菜单分类信息:
#             category = GoodsCategory.objects.get(id=category_id)
#         except GoodsCategory.DoesNotExist:
#             return http.HttpResponseNotFound('GoodsCategory 不存在')
#
#         # 查询商品频道分类
#         categories = get_categories()
#         # 查询面包屑导航
#         breadcrumb = get_breadcrumb(category)
#
#         # 接收sort参数：如果用户不传，就是默认的排序规则
#         sort = request.GET.get('sort', 'default')
#
#         # 按照排序规则查询该分类商品SKU信息
#         if sort == 'price':
#             # 按照价格由低到高
#             sortkind = 'price'
#         elif sort == 'hot':
#             # 按照销量由高到低
#             sortkind = '-sales'
#         else:
#             # 'price'和'sales'以外的所有排序方式都归为'default'
#             sort = 'default'
#             sortkind = 'create_time'#商品创建时间
#
#         # 获取当前分类并且上架的商品.( 并且对商品按照排序字段进行排序 )
#         skus = SKU.objects.filter(category=category,#最开始通过id获取的类别
#                                   is_launched=True).order_by(sortkind)#所有上架的
#
#         # 创建分页器：每页N条记录
#         # # 列表页每页商品数据量
#         # GOODS_LIST_LIMIT = 5
#         paginator = Paginator(skus, 5)#分页器，所有商品，每一页显示多少
#         # 获取每页商品数据
#         try:#page_skus，这个页对应的数据
#             page_skus = paginator.page(page_num)#page页面，传页码会把这一页对应的所有数据都显示
#         except EmptyPage:
#             # 如果page_num不正确，默认给用户404
#             return http.HttpResponseNotFound('empty page')
#         # 获取列表页总页数
#         total_page = paginator.num_pages#num_pages，总页面
#
#         # 渲染页面
#         context = {
#             'categories': categories,  # 频道分类
#             'breadcrumb': breadcrumb,  # 面包屑导航
#             'sort': sort,            # 排序字段
#             'category': category,  # 第三级分类
#             'page_skus': page_skus,  # 分页后数据
#             'total_page': total_page,  # 总页数
#             'page_num': page_num,  # 当前页码
#         }
#         return render(request, 'list.html', context)
import datetime
from django.utils import timezone
from django import http
from django.core.paginator import Paginator, EmptyPage
from django.shortcuts import render

# Create your views here.
from django.views import View

from goods.models import GoodsCategory, SKU, GoodsVisitCount
from goods.utils import get_categories, get_breadcrumb, get_goods_and_spec
from meiduo_mall.utils.response_code import RETCODE


class DetailVisitView(View):
    def post(self, request, category_id):
        '''
        保存当前类商品的访问次数
        :param request:
        :param category_id:
        :return:
        '''
        # 1.category_id查询对应的商品类别
        try:
            category = GoodsCategory.objects.get(id=category_id)
            # 根据category_id获得category表
        except GoodsCategory.DoesNotExist:
            return http.HttpResponseForbidden('此类商品不存在')

        # 2.获取当前时间
        t = timezone.localtime()

        today_str = '%d-%02d-%02d' % (t.year, t.month, t.day)

        today_date = datetime.datetime.strptime(today_str, '%Y-%m-%d')

        # 3.根据当前时间, 查询是否已经有当前商品的记录
        try:
            count_data = category.goodsvisitcount_set.get(date=today_date)
        except GoodsVisitCount.DoesNotExist:
            count_data = GoodsVisitCount()

        # 4.如果没有,创建一个新的记录
        try:
            # 5.更新记录(如果没有,其实就是添加)
            count_data.category = category
            count_data.count += 1
            count_data.save()
        except Exception as e:
            return http.HttpResponseServerError('保存失败')

        # 6.返回
        return http.JsonResponse({'code': RETCODE.OK,
                                  'errmsg': 'ok'})


class DetailView(View):
    def get(self, request, sku_id):
        '''
        返回商品详情页
        :param request:
        :param sku_id:
        :return:
        '''
        # 1.根据sku_id,获取对应的商品


        # 2.获取商品分类
        categories = get_categories()

        # 调用我们封装好的函数:
        data = get_goods_and_spec(sku_id, request)

        # 3.拼接参数
        context = {
            'categories': categories,
            'goods': data.get('goods'),
            'specs': data.get('goods_specs'),
            'sku': data.get('sku')
        }
        # 4.返回
        return render(request, 'detail.html', context)


class HotGoodsView(View):
    def get(self, request, category_id):
        '''
        商品热销排行(2个数据)
        :param request:
        :param category_id:
        :return:
        '''
        # sku中category_id就是自己的外键，orm映射，会自动加上id
        # 1.获取对应的商品(2) 条件: 满足当前id, 上架的, 排序, 截取
        skus = SKU.objects.filter(category_id=category_id,  # 此处是对象=对象，属性=属性
                                  is_launched=True).order_by('-sales')[:2]
        hot_skus = []

        # 2.整理格式
        for sku in skus:
            hot_skus.append({
                'id': sku.id,
                'default_image_url': sku.default_image_url,  # 图片
                'name': sku.name,  # 手机标题
                'price': sku.price  # 价格
            })

        # 3.返回(json)
        return http.JsonResponse({'code': RETCODE.OK,
                                  'errmsg': 'ok',
                                  'hot_skus': hot_skus})


class ListView(View):
    def get(self, request, category_id, page_num):
        '''
        接收参数, 返回list页面
        :param request:
        :param category_id:
        :param page_num:
        :return:
        '''
        # 1.根据category_id 获取商品分类
        try:
            category = GoodsCategory.objects.get(id=category_id)

        except GoodsCategory.DoesNotExist:
            return http.HttpResponseForbidden('goodscategory不存在')

        # 2.调用工具类方法, 获取商品分类
        categories = get_categories()

        # 3.根据工具类方法, 获取面包屑数据
        breadcrumb = get_breadcrumb(category)

        # 6. 获取查询字符串的参数
        sort = request.GET.get('sort', 'default')

        # 7. 判断参数类型, 决定排序的方式
        if sort == 'price':
            sortkind = 'price'
        elif sort == 'hot':
            sortkind = '-sales'
        else:
            sortkind = 'create_time'

        # 8. 获取该类别所对应的所有商品(经过排序的)
        skus = SKU.objects.filter(category=category,
                                  is_launched=True).order_by(sortkind)

        # 9. 创建分页器
        paginator = Paginator(skus, 5)

        # 10.根据前端传入的页码获取对应的所有商品.
        try:
            page_skus = paginator.page(page_num)
        except EmptyPage:
            return http.HttpResponseNotFound('当前没有发现')

        # 11. 创建变量,记录总页吗
        total_page = paginator.num_pages

        # 4.拼接参数
        # 渲染页面
        context = {
            'categories': categories,  # 频道分类
            'breadcrumb': breadcrumb,  # 面包屑导航
            'sort': sort,  # 排序字段
            'category': category,  # 第三级分类
            'page_skus': page_skus,  # 分页后数据
            'total_page': total_page,  # 总页数
            'page_num': page_num,  # 当前页码
        }
        # 5.返回

        return render(request, 'list.html', context)
